<template>
  <div class="cost-warning-page">
    <!-- 预警概览 -->
    <el-row :gutter="20" class="overview-cards">
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="overview-card">
          <div class="card-content">
            <div class="card-icon warning-total">
              <el-icon size="24"><Warning /></el-icon>
            </div>
            <div class="card-info">
              <div class="card-value">{{ warningOverview.totalWarnings }}</div>
              <div class="card-label">预警总数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="overview-card">
          <div class="card-content">
            <div class="card-icon warning-active">
              <el-icon size="24"><Bell /></el-icon>
            </div>
            <div class="card-info">
              <div class="card-value">{{ warningOverview.activeWarnings }}</div>
              <div class="card-label">活跃预警</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="overview-card">
          <div class="card-content">
            <div class="card-icon warning-handled">
              <el-icon size="24"><CircleCheck /></el-icon>
            </div>
            <div class="card-info">
              <div class="card-value">{{ warningOverview.handledWarnings }}</div>
              <div class="card-label">已处理</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="overview-card">
          <div class="card-content">
            <div class="card-icon warning-rules">
              <el-icon size="24"><SetUp /></el-icon>
            </div>
            <div class="card-info">
              <div class="card-value">{{ warningOverview.activeRules }}</div>
              <div class="card-label">预警规则</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 预警规则管理 -->
    <el-card style="margin-bottom: 20px">
      <template #header>
        <div class="page-header">
          <h3>预警规则管理</h3>
          <div class="header-actions">
            <el-button type="primary" @click="showRuleDialog">
              <el-icon><Plus /></el-icon>
              新建规则
            </el-button>
            <el-button type="success" @click="handleBatchEnable">
              <el-icon><Check /></el-icon>
              批量启用
            </el-button>
            <el-button type="warning" @click="handleBatchDisable">
              <el-icon><Close /></el-icon>
              批量禁用
            </el-button>
          </div>
        </div>
      </template>

      <!-- 规则筛选 -->
      <div class="search-area">
        <el-form :model="ruleSearchForm" inline>
          <el-form-item label="规则名称">
            <el-input 
              v-model="ruleSearchForm.ruleName" 
              placeholder="请输入规则名称" 
              clearable
            />
          </el-form-item>
          <el-form-item label="预警类型">
            <el-select v-model="ruleSearchForm.warningType" placeholder="请选择预警类型" clearable>
              <el-option label="成本超支预警" value="成本超支" />
              <el-option label="预算偏离预警" value="预算偏离" />
              <el-option label="成本率预警" value="成本率" />
              <el-option label="成本异常波动" value="成本异常" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="ruleSearchForm.status" placeholder="请选择状态" clearable>
              <el-option label="启用" value="启用" />
              <el-option label="禁用" value="禁用" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleRuleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleRuleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 规则表格 -->
      <el-table :data="ruleTableData" v-loading="ruleLoading" stripe>
        <el-table-column type="selection" width="55" />
        <el-table-column prop="ruleName" label="规则名称" width="180" />
        <el-table-column prop="warningType" label="预警类型" width="130">
          <template #default="{ row }">
            <el-tag :type="getWarningTypeTag(row.warningType)">
              {{ row.warningType }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="threshold" label="预警阈值" width="120" />
        <el-table-column prop="level" label="预警级别" width="100">
          <template #default="{ row }">
            <el-tag :type="getLevelTag(row.level)">
              {{ row.level }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="notifyWay" label="通知方式" width="150" />
        <el-table-column prop="notifyUsers" label="通知人员" width="150" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              active-value="启用"
              inactive-value="禁用"
              @change="handleStatusChange(row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="triggerCount" label="触发次数" width="100" align="center" />
        <el-table-column prop="createTime" label="创建时间" width="120" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEditRule(row)">
              编辑
            </el-button>
            <el-button type="warning" size="small" @click="handleTestRule(row)">
              测试
            </el-button>
            <el-button type="danger" size="small" @click="handleDeleteRule(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="rulePagination.currentPage"
          v-model:page-size="rulePagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="rulePagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleRuleSizeChange"
          @current-change="handleRuleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 预警记录 -->
    <el-card>
      <template #header>
        <div class="page-header">
          <h3>预警记录</h3>
          <div class="header-actions">
            <el-button @click="handleRefreshWarnings">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
            <el-button @click="handleExportWarnings">
              <el-icon><Download /></el-icon>
              导出
            </el-button>
          </div>
        </div>
      </template>

      <!-- 预警筛选 -->
      <div class="search-area">
        <el-form :model="warningSearchForm" inline>
          <el-form-item label="预警级别">
            <el-select v-model="warningSearchForm.level" placeholder="请选择预警级别" clearable>
              <el-option label="严重" value="严重" />
              <el-option label="警告" value="警告" />
              <el-option label="提示" value="提示" />
            </el-select>
          </el-form-item>
          <el-form-item label="处理状态">
            <el-select v-model="warningSearchForm.handleStatus" placeholder="请选择处理状态" clearable>
              <el-option label="待处理" value="待处理" />
              <el-option label="处理中" value="处理中" />
              <el-option label="已处理" value="已处理" />
              <el-option label="已忽略" value="已忽略" />
            </el-select>
          </el-form-item>
          <el-form-item label="日期范围">
            <el-date-picker
              v-model="warningSearchForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleWarningSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleWarningReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 预警表格 -->
      <el-table :data="warningTableData" v-loading="warningLoading" stripe>
        <el-table-column prop="warningNo" label="预警编号" width="150" fixed />
        <el-table-column prop="warningType" label="预警类型" width="130" />
        <el-table-column prop="level" label="预警级别" width="100">
          <template #default="{ row }">
            <el-tag :type="getLevelTag(row.level)" effect="dark">
              {{ row.level }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="warningContent" label="预警内容" width="300" show-overflow-tooltip />
        <el-table-column prop="targetName" label="预警对象" width="150" />
        <el-table-column prop="actualValue" label="实际值" width="120" align="right" />
        <el-table-column prop="thresholdValue" label="阈值" width="120" align="right" />
        <el-table-column prop="handleStatus" label="处理状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getHandleStatusTag(row.handleStatus)">
              {{ row.handleStatus }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="handler" label="处理人" width="100" />
        <el-table-column prop="warningTime" label="预警时间" width="160" />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button 
              v-if="row.handleStatus === '待处理'" 
              type="success" 
              size="small" 
              @click="handleWarning(row)"
            >
              处理
            </el-button>
            <el-button type="primary" size="small" @click="handleViewWarning(row)">
              详情
            </el-button>
            <el-button 
              v-if="row.handleStatus === '待处理'" 
              type="info" 
              size="small" 
              @click="handleIgnoreWarning(row)"
            >
              忽略
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="warningPagination.currentPage"
          v-model:page-size="warningPagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="warningPagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleWarningSizeChange"
          @current-change="handleWarningCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新建/编辑预警规则对话框 -->
    <el-dialog
      v-model="ruleDialogVisible"
      :title="ruleDialogTitle"
      width="700px"
      @close="handleRuleDialogClose"
    >
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="ruleFormRules"
        label-width="120px"
      >
        <el-form-item label="规则名称" prop="ruleName">
          <el-input v-model="ruleForm.ruleName" placeholder="请输入规则名称" />
        </el-form-item>

        <el-form-item label="预警类型" prop="warningType">
          <el-select v-model="ruleForm.warningType" placeholder="请选择预警类型" style="width: 100%">
            <el-option label="成本超支预警" value="成本超支" />
            <el-option label="预算偏离预警" value="预算偏离" />
            <el-option label="成本率预警" value="成本率" />
            <el-option label="成本异常波动" value="成本异常" />
          </el-select>
        </el-form-item>

        <el-form-item label="预警级别" prop="level">
          <el-select v-model="ruleForm.level" placeholder="请选择预警级别" style="width: 100%">
            <el-option label="严重" value="严重" />
            <el-option label="警告" value="警告" />
            <el-option label="提示" value="提示" />
          </el-select>
        </el-form-item>

        <el-form-item label="预警阈值" prop="threshold">
          <el-input v-model="ruleForm.threshold" placeholder="例如：>10% 或 >100000">
            <template #append>
              <el-select v-model="ruleForm.thresholdUnit" style="width: 100px">
                <el-option label="百分比" value="%" />
                <el-option label="金额" value="元" />
              </el-select>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="通知方式" prop="notifyWay">
          <el-checkbox-group v-model="ruleForm.notifyWay">
            <el-checkbox label="系统通知" />
            <el-checkbox label="邮件通知" />
            <el-checkbox label="短信通知" />
            <el-checkbox label="微信通知" />
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="通知人员" prop="notifyUsers">
          <el-select 
            v-model="ruleForm.notifyUsers" 
            multiple 
            placeholder="请选择通知人员" 
            style="width: 100%"
          >
            <el-option label="财务主管" value="财务主管" />
            <el-option label="成本会计" value="成本会计" />
            <el-option label="部门经理" value="部门经理" />
            <el-option label="总经理" value="总经理" />
          </el-select>
        </el-form-item>

        <el-form-item label="检查频率" prop="checkFrequency">
          <el-select v-model="ruleForm.checkFrequency" placeholder="请选择检查频率" style="width: 100%">
            <el-option label="实时检查" value="实时" />
            <el-option label="每小时" value="每小时" />
            <el-option label="每天" value="每天" />
            <el-option label="每周" value="每周" />
            <el-option label="每月" value="每月" />
          </el-select>
        </el-form-item>

        <el-form-item label="规则描述">
          <el-input 
            v-model="ruleForm.description" 
            type="textarea" 
            :rows="3"
            placeholder="请输入规则描述" 
          />
        </el-form-item>

        <el-form-item label="启用状态">
          <el-switch
            v-model="ruleForm.status"
            active-text="启用"
            inactive-text="禁用"
            active-value="启用"
            inactive-value="禁用"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="ruleDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleRuleSubmit" :loading="ruleSubmitLoading">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 预警详情对话框 -->
    <el-dialog
      v-model="warningDetailDialogVisible"
      title="预警详情"
      width="700px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="预警编号">{{ currentWarning.warningNo }}</el-descriptions-item>
        <el-descriptions-item label="预警类型">{{ currentWarning.warningType }}</el-descriptions-item>
        <el-descriptions-item label="预警级别">
          <el-tag :type="getLevelTag(currentWarning.level)" effect="dark">
            {{ currentWarning.level }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="预警对象">{{ currentWarning.targetName }}</el-descriptions-item>
        <el-descriptions-item label="实际值">{{ currentWarning.actualValue }}</el-descriptions-item>
        <el-descriptions-item label="阈值">{{ currentWarning.thresholdValue }}</el-descriptions-item>
        <el-descriptions-item label="处理状态">
          <el-tag :type="getHandleStatusTag(currentWarning.handleStatus)">
            {{ currentWarning.handleStatus }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="处理人">{{ currentWarning.handler || '未处理' }}</el-descriptions-item>
        <el-descriptions-item label="预警时间">{{ currentWarning.warningTime }}</el-descriptions-item>
        <el-descriptions-item label="处理时间">{{ currentWarning.handleTime || '未处理' }}</el-descriptions-item>
        <el-descriptions-item label="预警内容" :span="2">
          {{ currentWarning.warningContent }}
        </el-descriptions-item>
        <el-descriptions-item label="处理备注" :span="2">
          {{ currentWarning.handleRemark || '无' }}
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 处理预警对话框 -->
    <el-dialog
      v-model="handleDialogVisible"
      title="处理预警"
      width="500px"
    >
      <el-form
        ref="handleFormRef"
        :model="handleForm"
        :rules="handleFormRules"
        label-width="100px"
      >
        <el-form-item label="处理方式" prop="handleWay">
          <el-radio-group v-model="handleForm.handleWay">
            <el-radio label="已解决">已解决</el-radio>
            <el-radio label="待跟进">待跟进</el-radio>
            <el-radio label="忽略">忽略</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="处理说明" prop="handleRemark">
          <el-input 
            v-model="handleForm.handleRemark" 
            type="textarea" 
            :rows="4"
            placeholder="请输入处理说明" 
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="handleDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleWarningSubmit" :loading="handleSubmitLoading">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 响应式数据
const ruleLoading = ref(false)
const warningLoading = ref(false)
const ruleDialogVisible = ref(false)
const warningDetailDialogVisible = ref(false)
const handleDialogVisible = ref(false)
const ruleSubmitLoading = ref(false)
const handleSubmitLoading = ref(false)
const ruleFormRef = ref()
const handleFormRef = ref()
const ruleDialogTitle = ref('新建预警规则')

// 预警概览
const warningOverview = reactive({
  totalWarnings: 156,
  activeWarnings: 23,
  handledWarnings: 128,
  activeRules: 15
})

// 规则搜索表单
const ruleSearchForm = reactive({
  ruleName: '',
  warningType: '',
  status: ''
})

// 预警搜索表单
const warningSearchForm = reactive({
  level: '',
  handleStatus: '',
  dateRange: []
})

// 规则表单
const ruleForm = reactive({
  ruleName: '',
  warningType: '',
  level: '',
  threshold: '',
  thresholdUnit: '%',
  notifyWay: [],
  notifyUsers: [],
  checkFrequency: '',
  description: '',
  status: '启用'
})

// 规则表单验证
const ruleFormRules = {
  ruleName: [{ required: true, message: '请输入规则名称', trigger: 'blur' }],
  warningType: [{ required: true, message: '请选择预警类型', trigger: 'change' }],
  level: [{ required: true, message: '请选择预警级别', trigger: 'change' }],
  threshold: [{ required: true, message: '请输入预警阈值', trigger: 'blur' }],
  notifyWay: [{ required: true, message: '请选择通知方式', trigger: 'change' }],
  notifyUsers: [{ required: true, message: '请选择通知人员', trigger: 'change' }],
  checkFrequency: [{ required: true, message: '请选择检查频率', trigger: 'change' }]
}

// 处理表单
const handleForm = reactive({
  handleWay: '已解决',
  handleRemark: ''
})

// 处理表单验证
const handleFormRules = {
  handleWay: [{ required: true, message: '请选择处理方式', trigger: 'change' }],
  handleRemark: [{ required: true, message: '请输入处理说明', trigger: 'blur' }]
}

// 分页数据
const rulePagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

const warningPagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 当前预警
const currentWarning = reactive({})

// 规则表格数据
const ruleTableData = ref([
  {
    id: 1,
    ruleName: '成本超支10%预警',
    warningType: '成本超支',
    threshold: '>10%',
    level: '警告',
    notifyWay: '系统通知, 邮件通知',
    notifyUsers: '财务主管, 成本会计',
    status: '启用',
    triggerCount: 15,
    checkFrequency: '每天',
    createTime: '2024-01-01'
  },
  {
    id: 2,
    ruleName: '预算偏离20%严重预警',
    warningType: '预算偏离',
    threshold: '>20%',
    level: '严重',
    notifyWay: '系统通知, 邮件通知, 短信通知',
    notifyUsers: '财务主管, 总经理',
    status: '启用',
    triggerCount: 8,
    checkFrequency: '实时',
    createTime: '2024-01-01'
  },
  {
    id: 3,
    ruleName: '成本率异常提示',
    warningType: '成本率',
    threshold: '>75%',
    level: '提示',
    notifyWay: '系统通知',
    notifyUsers: '成本会计',
    status: '启用',
    triggerCount: 25,
    checkFrequency: '每周',
    createTime: '2024-01-05'
  },
  {
    id: 4,
    ruleName: '成本波动30%预警',
    warningType: '成本异常',
    threshold: '>30%',
    level: '警告',
    notifyWay: '系统通知, 邮件通知',
    notifyUsers: '财务主管, 部门经理',
    status: '禁用',
    triggerCount: 0,
    checkFrequency: '每天',
    createTime: '2024-01-10'
  }
])

// 预警表格数据
const warningTableData = ref([
  {
    id: 1,
    warningNo: 'W20240115001',
    warningType: '成本超支',
    level: '警告',
    warningContent: '智能手机X1本月成本超出预算12.5%，请及时关注',
    targetName: '智能手机X1',
    actualValue: '¥562,500',
    thresholdValue: '¥500,000',
    handleStatus: '待处理',
    handler: '',
    warningTime: '2024-01-15 10:30:00',
    handleTime: ''
  },
  {
    id: 2,
    warningNo: 'W20240115002',
    warningType: '预算偏离',
    level: '严重',
    warningContent: '智能手表W1成本偏离预算22%，已超过严重预警线',
    targetName: '智能手表W1',
    actualValue: '¥378,200',
    thresholdValue: '¥310,000',
    handleStatus: '处理中',
    handler: '张三',
    warningTime: '2024-01-15 11:20:00',
    handleTime: '2024-01-15 14:00:00'
  },
  {
    id: 3,
    warningNo: 'W20240114001',
    warningType: '成本率',
    level: '提示',
    warningContent: '平板电脑T1成本率达到76.8%，超过正常范围',
    targetName: '平板电脑T1',
    actualValue: '76.8%',
    thresholdValue: '75%',
    handleStatus: '已处理',
    handler: '李四',
    warningTime: '2024-01-14 16:45:00',
    handleTime: '2024-01-14 17:30:00'
  }
])

// 方法
const getWarningTypeTag = (type) => {
  const typeMap = {
    '成本超支': 'danger',
    '预算偏离': 'warning',
    '成本率': 'primary',
    '成本异常': 'info'
  }
  return typeMap[type] || 'info'
}

const getLevelTag = (level) => {
  const levelMap = {
    '严重': 'danger',
    '警告': 'warning',
    '提示': 'info'
  }
  return levelMap[level] || 'info'
}

const getHandleStatusTag = (status) => {
  const statusMap = {
    '待处理': 'danger',
    '处理中': 'warning',
    '已处理': 'success',
    '已忽略': 'info'
  }
  return statusMap[status] || 'info'
}

const loadRuleData = () => {
  ruleLoading.value = true
  setTimeout(() => {
    rulePagination.total = ruleTableData.value.length
    ruleLoading.value = false
  }, 500)
}

const loadWarningData = () => {
  warningLoading.value = true
  setTimeout(() => {
    warningPagination.total = warningTableData.value.length
    warningLoading.value = false
  }, 500)
}

const handleRuleSearch = () => {
  rulePagination.currentPage = 1
  loadRuleData()
}

const handleRuleReset = () => {
  Object.assign(ruleSearchForm, {
    ruleName: '',
    warningType: '',
    status: ''
  })
  handleRuleSearch()
}

const handleWarningSearch = () => {
  warningPagination.currentPage = 1
  loadWarningData()
}

const handleWarningReset = () => {
  Object.assign(warningSearchForm, {
    level: '',
    handleStatus: '',
    dateRange: []
  })
  handleWarningSearch()
}

const showRuleDialog = () => {
  ruleDialogTitle.value = '新建预警规则'
  ruleDialogVisible.value = true
  resetRuleForm()
}

const handleEditRule = (row) => {
  ruleDialogTitle.value = '编辑预警规则'
  Object.assign(ruleForm, {
    ruleName: row.ruleName,
    warningType: row.warningType,
    level: row.level,
    threshold: row.threshold.replace('>', '').replace('%', '').replace('元', ''),
    thresholdUnit: row.threshold.includes('%') ? '%' : '元',
    notifyWay: row.notifyWay.split(', '),
    notifyUsers: row.notifyUsers.split(', '),
    checkFrequency: row.checkFrequency,
    status: row.status
  })
  ruleDialogVisible.value = true
}

const handleDeleteRule = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该预警规则吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const index = ruleTableData.value.findIndex(item => item.id === row.id)
    if (index > -1) {
      ruleTableData.value.splice(index, 1)
      ElMessage.success('删除成功')
      loadRuleData()
    }
  } catch {
    // 用户取消操作
  }
}

const handleTestRule = (row) => {
  ElMessage.success(`规则"${row.ruleName}"测试通过`)
}

const handleStatusChange = (row) => {
  ElMessage.success(`规则已${row.status}`)
}

const handleBatchEnable = () => {
  ElMessage.info('批量启用功能开发中')
}

const handleBatchDisable = () => {
  ElMessage.info('批量禁用功能开发中')
}

const handleViewWarning = (row) => {
  Object.assign(currentWarning, row)
  warningDetailDialogVisible.value = true
}

const handleWarning = (row) => {
  Object.assign(currentWarning, row)
  handleDialogVisible.value = true
  resetHandleForm()
}

const handleIgnoreWarning = async (row) => {
  try {
    await ElMessageBox.confirm('确定要忽略该预警吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const index = warningTableData.value.findIndex(item => item.id === row.id)
    if (index > -1) {
      warningTableData.value[index].handleStatus = '已忽略'
      warningTableData.value[index].handler = '当前用户'
      warningTableData.value[index].handleTime = new Date().toLocaleString()
      ElMessage.success('已忽略')
      loadWarningData()
    }
  } catch {
    // 用户取消操作
  }
}

const handleRefreshWarnings = () => {
  loadWarningData()
  ElMessage.success('刷新成功')
}

const handleExportWarnings = () => {
  ElMessage.success('导出成功')
}

const handleRuleSubmit = async () => {
  if (!ruleFormRef.value) return

  try {
    await ruleFormRef.value.validate()
    ruleSubmitLoading.value = true

    await new Promise(resolve => setTimeout(resolve, 1000))

    const newRule = {
      id: Date.now(),
      ruleName: ruleForm.ruleName,
      warningType: ruleForm.warningType,
      threshold: `>${ruleForm.threshold}${ruleForm.thresholdUnit}`,
      level: ruleForm.level,
      notifyWay: ruleForm.notifyWay.join(', '),
      notifyUsers: ruleForm.notifyUsers.join(', '),
      status: ruleForm.status,
      triggerCount: 0,
      checkFrequency: ruleForm.checkFrequency,
      createTime: new Date().toLocaleDateString()
    }
    
    ruleTableData.value.unshift(newRule)
    ElMessage.success('预警规则创建成功')
    ruleDialogVisible.value = false
    loadRuleData()
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    ruleSubmitLoading.value = false
  }
}

const handleWarningSubmit = async () => {
  if (!handleFormRef.value) return

  try {
    await handleFormRef.value.validate()
    handleSubmitLoading.value = true

    await new Promise(resolve => setTimeout(resolve, 1000))

    const index = warningTableData.value.findIndex(item => item.id === currentWarning.id)
    if (index > -1) {
      warningTableData.value[index].handleStatus = '已处理'
      warningTableData.value[index].handler = '当前用户'
      warningTableData.value[index].handleTime = new Date().toLocaleString()
      warningTableData.value[index].handleRemark = handleForm.handleRemark
    }
    
    ElMessage.success('处理成功')
    handleDialogVisible.value = false
    loadWarningData()
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    handleSubmitLoading.value = false
  }
}

const handleRuleDialogClose = () => {
  resetRuleForm()
}

const resetRuleForm = () => {
  Object.assign(ruleForm, {
    ruleName: '',
    warningType: '',
    level: '',
    threshold: '',
    thresholdUnit: '%',
    notifyWay: [],
    notifyUsers: [],
    checkFrequency: '',
    description: '',
    status: '启用'
  })
  ruleFormRef.value?.clearValidate()
}

const resetHandleForm = () => {
  Object.assign(handleForm, {
    handleWay: '已解决',
    handleRemark: ''
  })
  handleFormRef.value?.clearValidate()
}

const handleRuleSizeChange = (size) => {
  rulePagination.pageSize = size
  loadRuleData()
}

const handleRuleCurrentChange = (page) => {
  rulePagination.currentPage = page
  loadRuleData()
}

const handleWarningSizeChange = (size) => {
  warningPagination.pageSize = size
  loadWarningData()
}

const handleWarningCurrentChange = (page) => {
  warningPagination.currentPage = page
  loadWarningData()
}

// 生命周期
onMounted(() => {
  loadRuleData()
  loadWarningData()
})
</script>

<style scoped>
.cost-warning-page {
  padding: 0;
}

.overview-cards {
  margin-bottom: 20px;
}

.overview-card {
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-content {
  display: flex;
  align-items: center;
}

.card-icon {
  width: 60px;
  height: 60px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  color: white;
}

.card-icon.warning-total {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.card-icon.warning-active {
  background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
}

.card-icon.warning-handled {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.card-icon.warning-rules {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.card-info {
  flex: 1;
}

.card-value {
  font-size: 32px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.card-label {
  font-size: 14px;
  color: #909399;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-header h3 {
  margin: 0;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

.search-area {
  margin-bottom: 20px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 4px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>

